class carBox {
    constructor() {
        this.getGoods()
        this.$('.cart-list').addEventListener('click', this.dispatch)
        this.$('.cart-th input').addEventListener('click', this.checkAll)
        //单选绑定
        
    }
    //取出商品信息的方法
    async getGoods() {
        //携带TOKEN令牌
        const AUTH_TOKEN = localStorage.getItem('token');
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        let res = await axios.get('http://localhost:8888/cart/list',
            {
                params: {
                    id: localStorage.getItem('user_id')
                }
            });
        // console.log(res);
        let data = res.data;
        let status = res.status;
        if (data.code == 1 && status == 200) {
            // console.log(data.cart);
            //模板拼接法
            let html = ''
            data.cart.forEach(goods => {
                // console.log(goods);
                html += `<ul class="goods-list yui3-g" data-id="${goods.goods_id}">
                <li class="yui3-u-3-8 pr">
                    <input type="checkbox" class="good-checkbox">
                    <div class="good-item">
                        <div class="item-img">
                            <img src="${goods.img_small_logo}">
                        </div>
                        <div class="item-msg">${goods.title}</div>
                    </div>
                </li>
                <li class="yui3-u-1-8">
                    <span>颜色: 银色</span>
                    <br>
                    <span>处理器: Core I5</span>
                    <br>
                    <span>内存: 8GB</span>
                    <br>
                    <span>尺寸: 13.3英寸</span>
                    <br>
                </li>
                <li class="yui3-u-1-8">
                    <span class="price">${goods.current_price}</span>
                </li>
                <li class="yui3-u-1-8">
                    <div class="clearfix">
                        <a href="javascript:;" class="increment mins">-</a>
                        <input autocomplete="off" type="text" value="${goods.cart_number}" minnum="1" class="itxt">
                        <a href="javascript:;" class="increment plus">+</a>
                    </div>
                    <div class="youhuo">有货</div>
                </li>
                <li class="yui3-u-1-8">
                    <span class="sum">${goods.current_price * goods.cart_number}</span>
                </li>
                <li class="yui3-u-1-8">
                    <div class="del1">
                        <a href="javascript:;" class="delete">删除</a>
                    </div>
                    <div>移到我的关注</div>
                </li>
            </ul>`
            });
            //追加到页面中
            this.$('.cart-list').innerHTML += html;
            //单个按钮事件绑定
            this. oneGoodsCheckBox()
        }
        //登录过期处理
        if(status == 200 && data.code == 401){
            localStorage.removeItem('token');
            localStorage.removeItem('user_id')
            location.assign('./login.html?ReturnUrl=./cart.html');
        }
    }
    //通过事件委托,实现购物车删除
    dispatch = (event) => {
        let target = event.target
        // console.log(target);
        //判断是否是按钮
        if (target.nodeName == 'A' && target.classList.contains('delete')) this.delGoods(target)
        //判断是否点击的是加号
        if(target.nodeName=='A'&& target.classList.contains('plus')) this.plusgoods(target)
        //判断是否是减号
        if(target.nodeName=='A'&& target.classList.contains('mins')) this.minsgoods(target)
    }
    //删除方法
    delGoods(tar) {
        //找到商品ID和商品iD弹出框询问是否需要删除
        layer.confirm('是否删除你的宝贝', {
            title: '删除警示'
        },
            function () {
                //确认
                // console.log('测试1');
                //无刷新获取UL
                let ul = tar.parentNode.parentNode.parentNode
                let gId = ul.dataset.id;
                let uId = localStorage.getItem('user_id')
                const AUTH_TOKEN = localStorage.getItem('token');
                axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
                let res = axios.get('http://localhost:8888/cart/remove', {
                    params: {
                        id: uId,
                        goodsId: gId
                    }
                }).then(res => {
                    // console.log(res);
                    //刷新删除
                    // location.reload()
                    //无刷新删除,关闭弹出框删除节点UL
                    layer.closeAll();
                    ul.remove()

                })

            }, function () {
                //取消
                // console.log('测试2');
            }
        )
    }
    //购物车全选择
    checkAll=(event)=>{
        // console.log(this);
        //点击全选的时候应该让单个商品的状态跟随全选,全部选中
        let allStatus=event.target.checked;
        // console.log(allStatus);
        this.oneCheck(allStatus)

        //统计数量价格放
        this.countSum();
    }
    //单个商品跟随全选的状态
    oneCheck(status){
        this.$('.good-checkbox').forEach(input=>{
            input.checked=status;
        })

    }
    //单选的实现
    oneGoodsCheckBox(){
        let self=this
        this.$('.good-checkbox').forEach(input=>{
            input.onclick=function(){
                // console.log(this.checked);
                //判断如果选择状态是取消,那么取消全选
                if(!this.checked){
                    self.$('.cart-th input').checked=false
                }
                //点击选中时则判断页面中是否有其他的未选中
               if(this.checked){
                  let  status= self.getOneGoodsStatus();
                  self.$('.cart-th input').checked=status

                  
               } 
               //将统计的方法引过来
               self.countSum()
            }
        })
    }

    //获取单个商品的选中状态
    getOneGoodsStatus(){
        //寻找是否有没有选中的
        let res=Array.from(this.$('.good-checkbox')).find(input=>{
            // console.log(input.checked);
            return !input.checked
        })
        // 如果res有值,则页面中有没被选中的
        //如果都被选中返TRUE
        return !res
    }
    //统计被选中商品的数量和产品的价格
    countSum(){
        let sum=0;
        let num=0;
        this.$('.good-checkbox').forEach(input=>{
            // console.log(input);
            if(input.checked){
                let ul=input.parentNode.parentNode;
                // console.log(ul);
                //获取数量和小鸡
                let tmpNum=ul.querySelector('.itxt').value-0;
                let tmpSum=ul.querySelector('.sum').innerHTML-0;
                // console.log(tmpNum,tmpSum);
                sum+=tmpSum;
                num+=tmpNum;
                // console.log(sum, num);
                
            }

        })
        sum=parseInt(sum*100)/100;
        // num=parseInt(sum*100)/100;
        // console.log(sum,num);
        this.$('.sumpreice-top strong').innerHTML=sum;
        this.$('.summoney span').innerHTML=sum

    }
    //数量增加的方法,箭头函数不同考虑this改变的问题
    plusgoods=(tar)=>{
        // console.log(tar);
        let ul=tar.parentNode.parentNode.parentNode;
        //数量
        let num=ul.querySelector('.itxt');
        //小鸡
        let sum=ul.querySelector('.sum');
        //单价
        let price=ul.querySelector('.price').innerHTML-0;
        // console.log(num,sum,price);
        //num进行加一操作
        //获取数量
        let numValue=num.value
        numValue++;
        // console.log(numValue);
        //更新到页面中,发送数据
        const AUTH_TOKEN = localStorage.getItem('token');
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        axios.defaults.headers['Content-type'] = 'application/x-www-form-urlencoded';
        let uId=localStorage.getItem('user_id');
        let gId=ul.dataset.id;
        let params=`id=${uId}&goodsId=${gId}&number=${numValue}`
        //拼接不能出现空格
        axios.post('http://localhost:8888/cart/number',params).then(res=>{
            // console.log(res);
            let {data,status}=res;
            if(data.code==1&&status==200){
                //将更新后的数量设置到页面
                num.value=numValue;
                
                sum.innerHTML=parseInt(numValue*price*100)/100 ;
                //调用统计的方法
                this.countSum();
            }
        })

    }
    //数量减少的方法
    minsgoods=(tar)=>{
        // console.log(tar);
        let ul=tar.parentNode.parentNode.parentNode;
        // console.log(ul);
        let num=ul.querySelector('.itxt');
        //小鸡
        let sum=ul.querySelector('.sum');
        //单价
        let price=ul.querySelector('.price').innerHTML-0;
        // console.log(num,sum,price);
        //num进行加一操作
        //获取数量
        let numValue=num.value
        numValue--;
        // console.log(numValue);
        //更新到页面中,发送数据
        const AUTH_TOKEN = localStorage.getItem('token');
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        axios.defaults.headers['Content-type'] = 'application/x-www-form-urlencoded';
        let uId=localStorage.getItem('user_id');
        let gId=ul.dataset.id;
        let params=`id=${uId}&goodsId=${gId}&number=${numValue}`
        //拼接不能出现空格
        axios.post('http://localhost:8888/cart/number',params).then(res=>{
            // console.log(res);
            let {data,status}=res;
            if(data.code==1&&status==200){
                //将更新后的数量设置到页面
                num.value=numValue;
                
                sum.innerHTML=parseInt(numValue*price*100)/100 ;
                //调用统计的方法
                this.countSum();
            }
        })
    }
    //获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res
    }
}
new carBox;